package com.xuxin.pda.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.zyapi.pos.PosManager;
import android.zyapi.pos.PrinterDevice;
import android.zyapi.pos.utils.BitmapTools;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.xuxin.pda.R;
import com.xuxin.pda.base.BaseConstant;
import com.xuxin.pda.base.BasePDAActivity;
import com.xuxin.pda.bean.CommitBean;
import com.xuxin.pda.bean.DepartmentBean;
import com.xuxin.pda.bean.TrashTypeBean;
import com.xuxin.pda.contract.TrashCollectContract;
import com.xuxin.pda.listener.PrinterListener;
import com.xuxin.pda.pda.BitmapPrinter;
import com.xuxin.pda.popup.ConfirmPopup;
import com.xuxin.pda.presenter.TrashCollectPresenter;
import com.xuxin.pda.utils.ACache;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020/12/24 0024
 * 医废收集
 */
public class TrashCollectActivity extends BasePDAActivity implements TrashCollectContract.View {
    private final TrashCollectContract.Presenter presenter = new TrashCollectPresenter(this);
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.trash_collect_name)
    TextView trash_collect_name;
    @BindView(R.id.trash_collect_department)
    TextView trash_collect_department;
    @BindView(R.id.trash_collect_type)
    TextView trash_collect_type;
    @BindView(R.id.trash_collect_weight)
    EditText trash_collect_weight;
    @BindView(R.id.trash_collect_connect)
    TextView trash_collect_connect;
    @BindView(R.id.trash_print)
    LinearLayout trash_print;

    private String userId;//用户id
    private String userNo;//用户编号
    private String userName;//用户名
    private String DepartmentCode;//科室代码
    private String dptName;//科室名称
    private String DepartmentId;//科室id
    private String DepartmentName;//科室
    private String PersonCharge;//负责人
    private String phone;//电话
    private String WorkNum;//编号
    private String Floor;//楼层
    private String Room;//房间
    private String trashType;//废物类型
    private String trashWeight;//废物重量
    private String ENum;//医生工号

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_trash_collect);
    }

    @Override
    public void initView() {
        title_name.setText("医废收集");
        button.setText("确认上传");
        title_right.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initData() {
        initPrint();
        ACache aCache = ACache.get(context);
        userId = aCache.getAsString(BaseConstant.userId);
        userNo = aCache.getAsString(BaseConstant.userNo);
        userName = aCache.getAsString(BaseConstant.userName);
        trash_collect_name.setText(userName);
        handler.sendEmptyMessage(0);
        /**
         * 测试
         */
         //ENum = "YS1213";DepartmentId = "KS10F";
        /**
         * 测试
         */
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.trash_collect_type, R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.trash_collect_type) {
            if (null != trashTypes) {
                new XPopup.Builder(context)
                        .maxWidth((int) (ScreenUtils.getScreenWidth() * 0.65))
                        .asCenterList("请选择废物类型", trashTypes, null, 0,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        trash_collect_type.setText(text);
                                    }
                                }, R.layout.popup_list, R.layout.popup_list_item)
                        .show();
            }
        } else if (id == R.id.button) {
            if (mPrinter.isPrinting()) {
                ToastUtils.showShort("正在打印中，请稍后。");
                return;
            }
            trashType = trash_collect_type.getText().toString();
            trashWeight = trash_collect_weight.getText().toString();
            if (StringUtils.isEmpty(trashType)) {
                ToastUtils.showShort("请选择废物类型");
                return;
            }
            if (StringUtils.isEmpty(trashWeight)) {
                ToastUtils.showShort("请填写废物重量");
                return;
            }
            if (StringUtils.isEmpty(ENum)) {
                ToastUtils.showShort("请扫描交接人员二维码");
                return;
            }
            if (StringUtils.isEmpty(DepartmentId)) {
                ToastUtils.showShort("请扫描科室二维码");
                return;
            }
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asCustom(new ConfirmPopup(context, "确定要提交打印吗？", new ConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            popup.setTitle("正在提交打印中...").show();
                            handler.sendEmptyMessageDelayed(2, 500);
                        }
                    })).show();
        }
    }

    @Override
    public void onSuccess(DepartmentBean departmentBean) {
        if (null != departmentBean.getResult()) {
            DepartmentName = departmentBean.getResult().getDept_Name();
            DepartmentId = departmentBean.getResult().getDepartmentId();
            Room = departmentBean.getResult().getRoomName();
            String context = "科室：" + DepartmentName + "\n"
                    + "房间：" + Room + "\n";
            trash_collect_department.setText(context);
        } else {
            DepartmentId = null;
            trash_collect_department.setText("");
        }
    }


    private String[] trashTypes;

    @Override
    public void onSuccess(TrashTypeBean trashTypeBean) {
        if (null != trashTypeBean && null != trashTypeBean.getResult()) {
            trashTypes = new String[trashTypeBean.getResult().getItems().size()];
            for (int i = 0; i < trashTypeBean.getResult().getItems().size(); i++) {
                trashTypes[i] = trashTypeBean.getResult().getItems().get(i).getCategoryName();
            }
        }
    }

    @Override
    public void onSuccess(CommitBean commitBean) {
        if (null != commitBean.getResult()) {
            try {
                print(commitBean);
                Bundle bundle = new Bundle();
                bundle.putSerializable(TrashResultActivity.RESULT, commitBean);
                ActivityUtils.startActivity(bundle, TrashResultActivity.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.getTrashType();
            } else if (msg.what == 1) {
                presenter.getDepartment(DepartmentId);
            } else if (msg.what == 2) {
                presenter.commit(userId, trashWeight, DepartmentId, trashType, ENum);
            }
            return false;
        }
    });

    /**
     * 初始化打印
     */
    private PrinterDevice mPrinter = null;

    private void initPrint() {
        mPrinter = PosManager.get().getPrinterDevice();
        mPrinter.setPrintEventListener(new PrinterListener());
        mPrinter.init();
    }

    /**
     * 开始打印
     */
    private void print(CommitBean commitBean) {
        if (mPrinter.isPrinting()) {
            ToastUtils.showShort("正在打印中，请稍后...");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("无锡明慈医院");
        PrinterDevice.TextData title = mPrinter.new TextData();
        mPrinter.addText(25, sb.toString());

        BitmapPrinter bpImage = new BitmapPrinter(this);
        bpImage.setBitmapSize(570, 380);
        String packageCode = commitBean.getResult().getPackageCode().substring(3);

        bpImage.addQrcode(commitBean.getResult().getPackageCode(), 200, 200, -30, 0);
        bpImage.addText("编号：" + packageCode, 20, 170, 40);
        bpImage.addText("类型：" + commitBean.getResult().getMedicalLittleClass(), 20, 170, 80);
        bpImage.addText("来源：" + commitBean.getResult().getDept_Name(), 20, 170, 120);
        bpImage.addText("重量：" + commitBean.getResult().getWeight_Kg()+"kg", 20, 170, 160);

        bpImage.addText("回收人：" + commitBean.getResult().getCollector(), 20, 0, 210);
        bpImage.addText("交接人：" + commitBean.getResult().getDoctorId(), 20, 0, 240);
        bpImage.addText("时间：" + TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm")), 20, 0, 270);

        Bitmap bmp = bpImage.getBitmap();
        bmp = BitmapTools.gray2Binary(bmp);
        byte[] printData = BitmapTools.bitmap2PrinterBytes(bmp);
        mPrinter.addBmp(25, 0, bmp.getWidth(), bmp.getHeight(), printData);

        bmp.recycle();
        mPrinter.printStart();
    }

    @Override
    public void onPDASuccess(String message) {
        if (message.startsWith("KS")) {
            DepartmentId = message;
            popup.setTitle("加载中...").show();
            handler.sendEmptyMessage(1);
        } else if (message.startsWith("YS")) {
            ENum = message;
            trash_collect_connect.setText(message);
        } else {
            ToastUtils.showShort("二维码格式错误");
        }
    }
}